package com.ukao.steward.ui.valetRunners.storeCreatOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.ukao.steward.R;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.OrderInfoBean;
import com.ukao.steward.bean.SearchUserBean;
import com.ukao.steward.bean.StoreBean;
import com.ukao.steward.bean.serviceTimeBean;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.PickerViewDialog;
import com.ukao.steward.dialog.PopWindowHelp;
import com.ukao.steward.pesenter.valetRunners.OrderSubmitPesenter;
import com.ukao.steward.ui.valetRunners.createOrder.AddressIdListFragment;
import com.ukao.steward.ui.valetRunners.storage.StorageListFragment;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.LocationUtils;
import com.ukao.steward.util.MyDateUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.OrderSubmitView;
import com.ukao.steward.widget.CustomPopWindow;
import com.ukao.steward.widget.StateButton;
import com.ukao.steward.widget.StateImageView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.hoang8f.android.segmented.SegmentedGroup;

import static com.ukao.steward.R.id.takeTime_start_end_tv;
import static com.ukao.steward.util.MyDateUtils.getTime;


public class OrderSubmitFragment extends MvpFragment<OrderSubmitPesenter> implements OrderSubmitView{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final int SEND_REQUEST_CODE = 1015;
    private static final int TALE_REQUEST_CODE = 1025;
    @BindView(R.id.back_tv)
    TextView backTv;
    @BindView(R.id.tab_one)
    RadioButton tabOne;

    @BindView(R.id.segmented_group)
    SegmentedGroup segmentedGroup;
    @BindView(R.id.subtract_btn)
    StateImageView subtractBtn;
    @BindView(R.id.count)
    EditText count;
    @BindView(R.id.add_btn)
    StateImageView addBtn;
    @BindView(R.id.takeDate)
    TextView takeDate;
    @BindView(R.id.take_time_layout)
    LinearLayout takeTimeLayout;
    @BindView(takeTime_start_end_tv)
    TextView takeTimeStartEndTv;
    @BindView(R.id.use_remark)
    TextView useRemark;
    @BindView(R.id.manage_remark)
    TextView manageRemark;
    @BindView(R.id.takeAddrId)
    TextView takeAddrId;
    @BindView(R.id.tab_three)
    RadioButton tabThree;
    @BindView(R.id.user_info_right_tab5)
    RadioButton userInfoRightTab5;
    @BindView(R.id.user_info_right_tab6)
    RadioButton userInfoRightTab6;
    @BindView(R.id.sendDate)
    TextView sendDate;
    @BindView(R.id.sendDate_layout)
    LinearLayout sendDateLayout;
    @BindView(R.id.sendAddrId)
    TextView sendAddrId;
    @BindView(R.id.sendAddrId_layout)
    LinearLayout sendAddrIdLayout;
    Unbinder unbinder;
    @BindView(R.id.tab_two)
    RadioButton tabTwo;
    @BindView(R.id.store_name)
    TextView storeName;
    @BindView(R.id.tab_four)
    RadioButton tabFour;
    @BindView(R.id.submit_btn)
    StateButton submitBtn;
    @BindView(R.id.takeTime_start_end_layout)
    LinearLayout takeTimeStartEndLayout;
    @BindView(R.id.takeAddrId_layout)
    LinearLayout takeAddrIdLayout;
    @BindView(R.id.sendAddrId_top_line)
    View sendAddrIdTopLine;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String useId;
    public String mapsendDate;
    public String mapTakeDate;
    private SearchUserBean mSearchUserBean;
    private String mapSendAddrId;
    private String mapTakeAddrId;
    private StringBuffer mStringBuffer;
    private LocationUtils mLocationUtils;
    private String storeId;
    private CustomPopWindow mStorePop;
    private List<StoreBean> mStoreData;
    private ArrayList<serviceTimeBean.ListBean> mServiceData;
    private OptionsPickerView mTimeBucketDialog;

    public static OrderSubmitFragment newInstance(SearchUserBean mSearchUserBean, String param2) {
        OrderSubmitFragment fragment = new OrderSubmitFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, mSearchUserBean);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSearchUserBean = getArguments().getParcelable(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected OrderSubmitPesenter createPresenter() {
        return new OrderSubmitPesenter(this);
    }

    @Override
    protected void initView() {
        takeDate.setText(getTime(Calendar.getInstance().getTime(), "MM—dd EEE"));
        sendDate.setText(getTime(Calendar.getInstance().getTime(), "MM—dd EEE"));
        mapTakeDate = MyDateUtils.getDate();
        mapsendDate = MyDateUtils.getDate();
        List<SearchUserBean.AddressListBean> mAaddressData = mSearchUserBean.getAddressList();
        mStringBuffer = new StringBuffer();
        if (!CheckUtils.isEmpty(mSearchUserBean.getAddressList())) {
            for (SearchUserBean.AddressListBean addressItem : mAaddressData) {
                if (addressItem.getDef() == 1) {
                    mapSendAddrId = addressItem.getId();
                    mapTakeAddrId = mapSendAddrId;
                    mStringBuffer.append(addressItem.getPhone())
                            .append(addressItem.getName() + "\n")
                            .append(addressItem.getRegionalDesc())
                            .append(addressItem.getDesc());
                    takeAddrId.setText(mStringBuffer.toString());
                    sendAddrId.setText(mStringBuffer.toString());
                }
            }

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_order_submit, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setStatusBarTintColor(R.color.colorPrimary);


    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnCheckedChanged({R.id.tab_one, R.id.tab_two, R.id.tab_three, R.id.tab_four})
    public void onChekChanged(CompoundButton view, boolean check) {
        if (check) {
            switch (view.getId()) {
                case R.id.tab_one:
                    showTakeRadio(check);
                    tabThree.setChecked(true);
                    break;
                case R.id.tab_two:
                    showTakeRadio(!check);
                    tabFour.setChecked(true);

                    break;
                case R.id.tab_three:
                    showsendRadio(check);
                    break;
                case R.id.tab_four:
                    showsendRadio(!check);


                    break;

            }
        }
    }

    /**
     * 取件方式 顾客送到店
     */
    public void showTakeRadio(boolean isUseSendStore) {
        takeTimeLayout.setVisibility(isUseSendStore ? View.GONE : View.VISIBLE);
        takeTimeStartEndLayout.setVisibility(isUseSendStore ? View.GONE : View.VISIBLE);
        takeAddrIdLayout.setVisibility(isUseSendStore ? View.GONE : View.VISIBLE);
    }


    /**
     * 送件方式  上门送件
     *
     * @param isUseTakeStore 是否是顾客到店取
     */
    private void showsendRadio(boolean isUseTakeStore) {
        sendDateLayout.setVisibility(isUseTakeStore ? View.GONE : View.VISIBLE);
        sendAddrIdLayout.setVisibility(isUseTakeStore ? View.GONE : View.VISIBLE);
        sendAddrIdTopLine.setVisibility(isUseTakeStore ? View.GONE : View.VISIBLE);
    }

    @OnClick({R.id.back_tv, R.id.add_btn,  R.id.takeAddrId_layout, R.id.sendDate_layout, R.id.sendAddrId_layout,
            R.id.submit_btn, R.id.store_name,R.id.takeTime_start_end_layout,R.id.subtract_btn,R.id.take_time_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case  R.id.takeTime_start_end_layout:

                    if (CheckUtils.isEmpty(mServiceData)){
                        mvpPresenter.serviceTime();
                    }else{
                        showTimeBucketDialog();
                    }

                break;
            case R.id.store_name:
                if (CheckUtils.isEmpty(mStoreData)) {
                    mvpPresenter.storelist();
                } else {
                    showPopStoreList();
                }

                break;
            case R.id.back_tv:
                finish();
                break;
            case R.id.subtract_btn:/*减去*/
                if (!CheckUtils.isEmpty(getText(count))) {
                    int clothingCount = Integer.valueOf(getText(count));
                    if (clothingCount > 0) {
                        clothingCount = clothingCount - 1;
                        String strclothingCount = String.valueOf(clothingCount);
                        count.setText(strclothingCount);
                        count.setSelection(strclothingCount.length());
                    }
                }


                break;

            case R.id.submit_btn:
                if (CheckUtils.isEmpty(storeId)) {
                    T.show("请选择店铺");
                    return;
                } else if (CheckUtils.isEmpty(mapSendAddrId) && tabTwo.isChecked()) {
                    T.show("请添加地址");
                    return;
                } else if (CheckUtils.isEmpty(mapSendAddrId) && tabFour.isChecked()) {
                    T.show("请添加地址");
                    return;
                }

                HashMap mHashMap = new HashMap<String, String>();

                mHashMap.put("storeId", storeId);
                mHashMap.put("userId", mSearchUserBean.getUserId());
                mHashMap.put("createCnt", getText(count));
                String priority = userInfoRightTab5.isChecked() ? "0" : "1";
                String takeMode = tabOne.isChecked() ? "1" : "2";
                String sendMode = tabThree.isChecked() ? "1" : "2";
                mHashMap.put("priority", priority);/*订单优先级 0.普通 1.加急*/
                mHashMap.put("takeMode", takeMode);/*取件方式1.客户送到店 2.上门取件*/
                mHashMap.put("sendMode", sendMode);/*送件方式 1.客户到店取 2.上门送件*/
                mHashMap.put("userRemark", getText(useRemark));/*用户订单备注*/
                if (tabOne.isChecked()) {
                    mHashMap.put("takeDate", "");/*取件(衣)日期*/
                } else {
                    String[] takeTime = getText(takeTimeStartEndTv).split("-");
                    mHashMap.put("takeDate", mapTakeDate);/*取件(衣)日期*/
                    if (takeTime.length == 2) {
                        mHashMap.put("takeTimeStart", takeTime[0]);/*取件(衣)起始时间段*/
                        mHashMap.put("takeTimeEnd", takeTime[1]);/*取件(衣)起始时间段*/
                    }else{
                        mHashMap.put("takeTimeStart", "");/*取件(衣)起始时间段*/
                        mHashMap.put("takeTimeEnd", "");/*取件(衣)起始时间段*/
                    }
                }
                if (tabTwo.isChecked()) {
                    mHashMap.put("takeAddressId", mapTakeAddrId);
                }//取件用户地址id
                if (tabFour.isChecked()) {
                    mHashMap.put("sendDate", mapsendDate);/*送件(衣)日期*/
                    mHashMap.put("sendAddressId", mapSendAddrId);//送件用户地址id
                }
                mHashMap.put("remark", getText(manageRemark));/*订单管理备注*/
                mHashMap.put("accessToken", SaveParams.getToken());
                L.i("mHashMap=" + mHashMap.toString());
                mvpPresenter.orderAdd(mHashMap);
                break;

            case R.id.add_btn:/*加*/
                String strcount = getText(count);
                if (!CheckUtils.isEmpty(strcount)) {
                    int clothingCount1 = Integer.valueOf(strcount);
                    clothingCount1 = clothingCount1 + 1;
                    String strclothingCount1 = String.valueOf(clothingCount1);
                    count.setText(strclothingCount1);
                    count.setSelection(strclothingCount1.length());
                } else {
                    count.setText("1");
                    count.setSelection(1);
                }

                break;
            case R.id.take_time_layout:
                PickerViewDialog.getInstance().showDateQuantumPicker(6, takeDate, sendDate, _mActivity, (date, v) -> {
                    mapTakeDate = MyDateUtils.formatDate(date);
                    takeDate.setText(getTime(date, "MM—dd EEE"));
                });
                break;
            case R.id.takeAddrId_layout:

                startForResult(AddressIdListFragment.newInstance(mSearchUserBean.getName(),
                        mSearchUserBean.getPhone(),
                        mSearchUserBean.getUserId()),
                        TALE_REQUEST_CODE);

                break;

            case R.id.sendDate_layout:
                PickerViewDialog.getInstance().showDateQuantumPicker(30, takeDate, sendDate, _mActivity, (date, v) -> {
                    mapsendDate = MyDateUtils.formatDate(date);
                    sendDate.setText(getTime(date, "MM—dd EEE"));
                });
                break;
            case R.id.sendAddrId_layout:
                startForResult(AddressIdListFragment.newInstance(mSearchUserBean.getName(),
                        mSearchUserBean.getPhone(),
                        mSearchUserBean.getUserId()),
                        SEND_REQUEST_CODE);
                break;
        }
    }

    void showPopStoreList() {
        if (CheckUtils.isEmpty(mStoreData)) return;
        mStorePop = PopWindowHelp.showPopStoreList(storeName, _mActivity, mStoreData, position -> {
                    StoreBean mItem = mStoreData.get(position);
                    if (mItem != null) {
                        if (mItem.isCheck()) return;
                        mStorePop.dissmiss();
                        mItem.setCheck(true);
                        for (int i = 0; i < mStoreData.size(); i++) {
                            StoreBean storeBean = mStoreData.get(i);
                            if (mStoreData.indexOf(mItem) != i) {
                                storeBean.setCheck(false);
                            }
                        }
                        storeId = mItem.getId();
                        storeName.setText(CheckUtils.isEmptyString(mItem.getName()));


                    }
                }

        );

    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            SearchUserBean.AddressListBean mItem = data.getParcelable(ARG_PARAM1);
            switch (requestCode) {
                case SEND_REQUEST_CODE:
                    setForResultAddressData(mItem);
                    sendAddrId.setText(mStringBuffer.toString());
                    mapSendAddrId = mItem.getId();
                    break;
                case TALE_REQUEST_CODE:
                    setForResultAddressData(mItem);
                    takeAddrId.setText(mStringBuffer.toString());
                    mapTakeAddrId = mItem.getId();
                    break;


            }
        }

    }

    void setForResultAddressData(SearchUserBean.AddressListBean mItem) {

        if (mStringBuffer == null) mStringBuffer = new StringBuffer();
        mStringBuffer.setLength(0);
        mStringBuffer.append(mItem.getPhone())
                .append(mItem.getName() + "\n")
                .append(mItem.getRegionalDesc())
                .append(mItem.getDesc());
    }


    @Override
    public void storelistSucceed(List<StoreBean> mStoreData) {
        this.mStoreData = mStoreData;
        showPopStoreList();
    }

    @Override
    public void serviceTimeSucceed(ArrayList<serviceTimeBean.ListBean> mServiceTime) {
        this.mServiceData= mServiceTime;
            if (CheckUtils.isEmpty(mServiceData)) return;
            showTimeBucketDialog();


    }

    @Override
    public void orderAddSucceed(OrderInfoBean mOrderBean) {
        start( StorageListFragment
                .createBuilder()
                .orderId(mOrderBean.getId())
                .orderNo(mOrderBean.getOrderNo())
                .build(),SINGLETASK);

    }

    void showTimeBucketDialog() {

            mTimeBucketDialog = PickerViewDialog.getInstance().ShowCityPickerView(_mActivity, "取件时间段",
                    (options1, options2, options3, v) ->
                            takeTimeStartEndTv.setText(mServiceData.get(options1).getTime()));
            mTimeBucketDialog.setPicker(mServiceData);
            mTimeBucketDialog.show();

        
    }

}
